package com.linln.admin.metadata.templateField.controller;

import com.linln.admin.metadata.template.domain.MetadataTemplateDO;
import com.linln.admin.metadata.template.service.MetadataTemplateDOService;
import com.linln.admin.metadata.templateField.domain.MetadataFieldDO;
import com.linln.admin.metadata.templateField.service.MetadataFieldDOService;
import com.linln.admin.metadata.templateField.validator.MetadataFieldDOValid;
import com.linln.common.enums.StatusEnum;
import com.linln.common.utils.EntityBeanUtil;
import com.linln.common.utils.ResultVoUtil;
import com.linln.common.utils.StatusUtil;
import com.linln.common.vo.ResultVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author leuyius
 * @date 2020/03/18
 */
@Controller
@RequestMapping("/metadata/templateField")
public class MetadataFieldDOController {

    @Autowired
    private MetadataFieldDOService metadataFieldDOService;

    @Autowired
    private MetadataTemplateDOService metadataTemplateDOService;

    /**
     * 列表页面
     */
    @GetMapping("/index")
    @RequiresPermissions("metadata:templateField:index")
    public String index(Model model, MetadataFieldDO metadataFieldDO) {

        // 创建匹配器，进行动态查询匹配
        ExampleMatcher matcher = ExampleMatcher.matching();

        // 获取数据列表
        Example<MetadataFieldDO> example = Example.of(metadataFieldDO, matcher);
        Page<MetadataFieldDO> list = metadataFieldDOService.getPageList(example);

        // 封装数据
        model.addAttribute("list", list.getContent());
        model.addAttribute("page", list);
        return "/metadata/templateField/index";
    }

    /**
     * 跳转到添加页面
     */
    @GetMapping("/add")
    @RequiresPermissions("metadata:templateField:add")
    public String toAdd(Model model) {
        findMetadataTemplates(model);
        return "/metadata/templateField/add";
    }

    /**
     * 跳转到编辑页面
     */
    @GetMapping("/edit/{id}")
    @RequiresPermissions("metadata:templateField:edit")
    public String toEdit(@PathVariable("id") MetadataFieldDO metadataFieldDO, Model model) {
        model.addAttribute("metadataFieldDO", metadataFieldDO);
        findMetadataTemplates(model);
        return "/metadata/templateField/add";
    }

    /**
     * 获取当前满足条件的元数据模板
     * @param model
     */
    private void findMetadataTemplates(Model model){
        List<MetadataTemplateDO> metadataTemplates = metadataTemplateDOService.getTemplatesByTemplateType(0);
        Map<Long, String> templates = new TreeMap<>();
        metadataTemplates.stream().forEach(metadataTemplateDO -> {
            templates.put(Long.valueOf(String.valueOf(metadataTemplateDO.getId())), String.valueOf(metadataTemplateDO.getViewName()));
        });
        model.addAttribute("metadataTemplates", templates);
    }

    /**
     * 保存添加/修改的数据
     * @param valid 验证对象
     */
    @PostMapping("/save")
    @RequiresPermissions({"metadata:templateField:add", "metadata:templateField:edit"})
    @ResponseBody
    public ResultVo save(@Validated MetadataFieldDOValid valid, MetadataFieldDO metadataFieldDO) {
        // 复制保留无需修改的数据
        if (metadataFieldDO.getId() != null) {
            MetadataFieldDO beMetadataFieldDO = metadataFieldDOService.getById(metadataFieldDO.getId());
            EntityBeanUtil.copyProperties(beMetadataFieldDO, metadataFieldDO);
        }

        // 保存数据
        metadataFieldDOService.save(metadataFieldDO);
        return ResultVoUtil.SAVE_SUCCESS;
    }

    /**
     * 跳转到详细页面
     */
    @GetMapping("/detail/{id}")
    @RequiresPermissions("metadata:templateField:detail")
    public String toDetail(@PathVariable("id") MetadataFieldDO metadataFieldDO, Model model) {
        model.addAttribute("metadataFieldDO",metadataFieldDO);
        return "/metadata/templateField/detail";
    }

    /**
     * 设置一条或者多条数据的状态
     */
    @RequestMapping("/status/{param}")
    @RequiresPermissions("metadata:templateField:status")
    @ResponseBody
    public ResultVo status(
            @PathVariable("param") String param,
            @RequestParam(value = "ids", required = false) List<Long> ids) {
        // 更新状态
        StatusEnum statusEnum = StatusUtil.getStatusEnum(param);
        if (metadataFieldDOService.updateStatus(statusEnum, ids)) {
            return ResultVoUtil.success(statusEnum.getMessage() + "成功");
        } else {
            return ResultVoUtil.error(statusEnum.getMessage() + "失败，请重新操作");
        }
    }
}